﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using timetableasy.Models;
using System.Web.ApplicationServices;
using timetableasy.Helpers;

namespace timetableasy.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {
        RoleRepository _roleRepository = new RoleRepository();
        CampusManagerUserRepository _campusManagerUserRepository = new CampusManagerUserRepository();
        // This constructor is used by the MVC framework to instantiate the controller using
        // the default forms authentication and membership providers.
        public AccountController()
            : this(null, null)
        {
        }

        // This constructor is not used by the MVC framework but is instead provided for ease
        // of unit testing this type. See the comments in AccountModels.cs for more information.
        public AccountController(IFormsAuthenticationService formsService, IMembershipService membershipService)
        {
            FormsService = formsService ?? new FormsAuthenticationService();
            MembershipService = membershipService ?? new AccountMembershipService();
        }

        public IFormsAuthenticationService FormsService
        {
            get;
            private set;
        }

        public IMembershipService MembershipService
        {
            get;
            private set;
        }

        protected override void Initialize(RequestContext requestContext)
        {
            if (requestContext.HttpContext.User.Identity is WindowsIdentity)
            {
                throw new InvalidOperationException("Windows authentication is not supported.");
            }
            else
            {
                base.Initialize(requestContext);
            }
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

            base.OnActionExecuting(filterContext);
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
            Justification = "Needs to take same parameter type as Controller.Redirect()")]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.Login, model.Password))
                {
                    FormsService.SignIn(model.Login, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }        

        public ActionResult Register()
        {
            //// Create Roles view data
            //var RolesList = new SelectList(Roles.GetAllRoles(), "RoleId", "RoleName");
            //ViewData["Roles"] = RolesList;

            //// Create CampusId view data
            //var campusList = new CascadingSelectList(CampusManagerUser., "MakeId", "Id", "Name");
            //ViewData["Models"] = campusList;

            //return View("Index");


            User u = new Models.User();
            ViewData["Roles"] = new SelectList(Roles.GetAllRoles(),u.aspnet_Role); 
            return View();
        }

        [HttpGet]
        public ActionResult RegisterBis(string role)
        {
            switch(role)
            {
                case "Speaker": return Redirect("RegisterSpeaker");
                case "Campus Manager": return Redirect("RegisterCampusManager");
                case "Admin": return Redirect("RegisterAdmin");
                case "Student": return Redirect("RegisterStudent");
                default : return RedirectToAction("Register");
            }
        }

        public ActionResult RegisterSpeaker()
        {
            return View();
        }

        [HttpPost]
        public ActionResult RegisterSpeaker(User userModel)
        {
            return RegisterUserModel(userModel, "Speaker");
        }


        public ActionResult RegisterCampusManager()
        {
            CampusRepository cr = new CampusRepository();
            ViewData["Campuses"] = new SelectList(cr.GetAllCampusesNames());
            CampusManagerUser cmu = new CampusManagerUser
            {
                FirstName = "test",
                LastName = "test",
                Login = "test" + new Random().Next(100).ToString(),
                Email = "test@test.com"
            };

            return View(cmu);
        }

        [HttpPost]
        public ActionResult RegisterCampusManager(string CampusName, User userModel)
        {
            CampusManagerUser um = new CampusManagerUser(userModel);
            um.CampusName = CampusName;
            return RegisterUserModel<CampusManagerUser>(um, "Campus Manager");
        }


        public ActionResult RegisterClassManager()
        {
            ClassRepository cr = new ClassRepository();
            ViewData["Classes"] = new SelectList(cr.GetAllClassesNames()); 
            return View();
        }

        [HttpPost]
        public ActionResult RegisterClassManager(string ClassName, User userModel)
        {
            ClassManagerUser cmu = new ClassManagerUser(userModel);
            cmu.ClassName = ClassName;
            return RegisterUserModel<ClassManagerUser>(cmu, "Class Manager");
        }


        public ActionResult RegisterAdmin()
        {
            return View();
        }

        [HttpPost]
        public ActionResult RegisterAdmin(User model)
        {
            return RegisterUserModel(model, "Admin");
        }

        
        public ActionResult RegisterStudent()
        {
            return View();
        }

        [HttpPost]
        public ActionResult RegisterStudent(User model)
        {
            return RegisterUserModel(model, "Student");
        }

        public ActionResult RegisterUserModel<T>(T userModel, string role) where T : User
        {
            userModel.aspnet_Role = _roleRepository.GetRoleByName(role);
            userModel.RoleName = role;
            userModel.UserRoleIdFK = _roleRepository.GetRoleIdByName(role);
            return RegisterAccount(userModel);
        }

        public ActionResult RegisterAccount<T>(T model) where T : User
        {
            
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Login, model.Password, model.Email);
                
                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.Login, false /* createPersistentCookie */);
                    CreateEditProfile<T>(model);
                    CreateUser(model,ModelState);
                    //return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Login already exists. Please enter a different login.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The login provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

        public void CreateEditProfile<T>(T model) where T : User
        {
            MembershipUser user = Membership.GetUser(model.Login);
            ProfileCommon profile = ProfileCommon.Create(user.UserName, user.IsApproved) as ProfileCommon;

            profile.FirstName = model.FirstName;
            profile.LastName = model.LastName;
            profile.Save();
        }

        public virtual ModelStateDictionary CreateUser<T>(T model, ModelStateDictionary m) where T : User
        {
            try
            {
                CampusManagerUserRepository _camuRepository;
                StudentUserRepository _suRepository;
                ClassManagerUserRepository _cmuRepository;
                UserRepository _uRepository;
                if (model is CampusManagerUser)
                {
                    _camuRepository = new CampusManagerUserRepository();
                    _camuRepository.Add(model as CampusManagerUser);
                    _camuRepository.Save();
                }
                else if (model is StudentUser)
                {
                    _suRepository = new StudentUserRepository();
                    _suRepository.Add(model as StudentUser);
                    _suRepository.Save();
                }
                else if (model is ClassManagerUser)
                {
                    _cmuRepository = new ClassManagerUserRepository();
                    _cmuRepository.Add(model as ClassManagerUser);
                    _cmuRepository.Save();
                }
                else if (model is AdminUser)
                {
                    _uRepository = new UserRepository();
                    _uRepository.Add(model as AdminUser);
                    _uRepository.Save();
                }  
                else
                {
                    _uRepository = new UserRepository();
                    _uRepository.Add(model as SpeakerUser);
                    _uRepository.Save();
                }
            }
            catch
            {
                foreach (var issue in model.GetRuleViolations())
                {
                    m.AddModelError(issue.PropertyName, issue.ErrorMessage);
                }
            }
            return m;
        }

        public void SaveUser<T>(T model) 
            where T : User
        {
            
        }
    }
}
